package com.sbio.udiapp.net.response;

import com.sbio.udiapp.net.bean.AjaxResult;
import com.sbio.udiapp.net.exception.ApiException;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * 获取AjaxResult后判断请求结果，并获取data返回
 * Observable<AjaxResult> 转换为 Observable<T>
 * @param <T>
 */
public class ResponseTransformer<T> implements ObservableTransformer<AjaxResult, AjaxResult> {

    private CompositeDisposable compositeDisposable;

    public ResponseTransformer(CompositeDisposable compositeDisposable) {
        this.compositeDisposable = compositeDisposable;
    }

    public ResponseTransformer() {
    }

    @Override
    public ObservableSource<AjaxResult> apply(Observable<AjaxResult> upstream) {
        Observable<AjaxResult> ajaxResultObservable = upstream.doOnSubscribe(disposable -> {
                    if (compositeDisposable != null) {
                        compositeDisposable.add(disposable);
                    }
                })
                .onErrorResumeNext(throwable -> {
                    return Observable.error(ApiException.handleException(throwable));
                })
                .flatMap((Function<AjaxResult, ObservableSource<AjaxResult>>) ajaxResult -> {

                    if (ajaxResult.isSuccess()) {
                        /*T data = ajaxResult.getData();
                        if (data != null) {
                            return Observable.just(data);
                        }

                        data = (T) "";*/
                        return Observable.just(ajaxResult);

                    }
                    return Observable.error(new ApiException(ajaxResult.getCode(), ajaxResult.getMsg()));
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
        return ajaxResultObservable;
    }

    public static <U> ResponseTransformer<U> obtain(){
        return new ResponseTransformer<>();
    }

    public static <U> ResponseTransformer<U> obtain(CompositeDisposable compositeDisposable){
        return new ResponseTransformer<>(compositeDisposable);
    }
}
